// 初始化
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const authRoutes = require('./routes/auth');
const blogRoutes = require('./routes/blogs'); // Ensure this path is correct
const tagRoutes = require('./routes/tags');
const fileRoutes = require('./routes/file');
const sequelize = require('./config/database');
const authMiddleware = require("./middleware/authMiddleware");

const app = express();

// 中间件
// 用来解析 post body x-www-form-urlencoded 格式化数据
app.use(bodyParser.urlencoded({ extended: false }));
// 用来解析 post body json 格式化数据
app.use(bodyParser.json());
// 跨域
app.use(cors());
// 提供静态资源
app.use("/tempFiles", express.static(path.join(__dirname, 'tempFiles')));

// 路由
app.use('/auth', authRoutes);

// 除了登录和注册接口之外，其它所有的接口都会走鉴权中间件
app.use(authMiddleware);
app.use('/blog', blogRoutes);
app.use('/tags', tagRoutes);
app.use('/upload', fileRoutes);

// 同步数据库
sequelize.sync()
    .then(() => {
        console.log("Database synced");
    })
    .catch(err => {
        console.log(err);
    })

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});
